<?php

namespace App\Http\Controllers;

use App\Lib\Util\ErrorCode;
use Illuminate\Http\Request;
//use Laravel\Lumen\Http\Request;
use Mockery\Exception;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    /**
     * @param Request $req
     * @param string $apiv 版本号
     * @param string $module 模块
     * @param string $ctl 控制器
     * @param string $action 动作
     * @throws \mixed
     * @desc BdApi入口
     */
    public function Api(Request $req,$apiv, $module, $ctl, $action)
    {

        if (empty($apiv) || empty($module) || empty($ctl)) {
            throw new Exception('', ErrorCode::PARAMS_ERROR);
        }
        $versionIndex = intval(substr($apiv, 1));

        if ($versionIndex < 1) {
            throw new Exception('', ErrorCode::ERROR_CODE);
        }

        $max = 100;  #定义最大查找版本次数

        $project = $req->segment(1);

        while ($max > 0 && $versionIndex > 0) {
            //组装版本V
            $apiv = 'v' . $versionIndex;
            //组装controller的名字
            $ctlName = __NAMESPACE__ . '\\'
                . ucfirst($project) . '\\' . ucfirst($apiv) . '\\' . ucfirst($module) . '\\' . ucfirst($ctl) . 'Controller';
            if (class_exists($ctlName)) {
                $ctl_obj = app($ctlName);
                if (method_exists($ctl_obj, $action)) {
                    return $ctl_obj->$action($req);
                } else {
                    throw new Exception('', ErrorCode::SYSTEM_CTL_ACTION_NOT_FOUND);
                }
                break;
            } else {
                throw new Exception('', ErrorCode::SYSTEM_CTL_NOT_FOUND);
            }

            $versionIndex--;
            $max--;
        }
    }


    /**
     * @param Request $req
     * @param string $module 模块名
     * @param string $class 类名&文件名
     * @param string $action 动作名
     * @return \Illuminate\Http\JsonResponse
     * @desc    后台入口
     */
    public function Admin(Request $req, $module, $ctl, $action)
    {
        $project = $req->segment(1);

        $ctlName = __NAMESPACE__ . '\\' . ucfirst($project) . '\\' . ucfirst($module) . '\\' . ucfirst($ctl) . 'Controller';
        if (class_exists($ctlName)) {
            $ctl_obj = app($ctlName);
            if (method_exists($ctl_obj, $action)) {
                return $ctl_obj->$action($req);
            } else {
                throw new Exception('', ErrorCode::SYSTEM_CTL_ACTION_NOT_FOUND);
            }
        } else {
            throw new Exception('', ErrorCode::SYSTEM_CTL_NOT_FOUND);
        }
    }
}
